#include<dirent.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<time.h>
#include<stdarg.h> //for var_start and var_end
#include<sqlite3.h>
/*how to use
 * make -o scandir scanDir.c -lsqlite3
 * ./scandir folder
*/

#define DB "scandb"
sqlite3 *db;

struct nodeElement
{
	char name[128];
	char *pathname;
	int kind;
	long mtime;
	long size;
};

struct nodes
{
	struct nodeElement element;
	struct nodes *next;
};

void LOG(char *format, ...)
{
	va_list ap;
	int ret;
	char buf[1024]={0},tmp_buf[1024]={0};
	time_t rawtime;
	struct tm *timei;
	char b_date[128]={0};
	struct stat logf;
	int result;

	va_start(ap,format);
	ret=vsprintf(buf,format,ap);
	va_end(ap);
	if(ret >=0){
		result =stat("scanlog",&logf);
		if (result !=0)
			printf("show fail\n");
		int size=logf.st_size;
		if(size >=1024*1024*1)
			system("echo clear > scanlog");
		time(&rawtime);
		timei=localtime(&rawtime);
		sprintf(b_date,"%d.%d.%d-%d:%d:%d",timei->tm_year+1900,timei->tm_mon+1,timei->tm_mday,\
				timei->tm_hour,timei->tm_min,timei->tm_sec);
		FILE *am_fp=fopen("scanlog","a");
		sprintf(tmp_buf,"[%s]%s",b_date,buf);
		fprintf(am_fp,tmp_buf);
		fclose(am_fp);
		printf(buf);
	}
}

int printnodes(struct nodes *ns)
{
	struct nodes *tmp;
	for(tmp=ns->next;tmp;tmp=tmp->next)
		LOG("name:%s",tmp->element.name);
}

int createtable(sqlite3 *db){
	LOG("create DB table");
	char *err_msg=0;
	char *sql="CREATE TABLE IF NOT EXISTS NODES(id INTEGER PRIMARY KEY,name TEXT,kind INTEGER,parentname TEXT)";
	int rc=sqlite3_exec(db,sql,0,0,&err_msg);
	if(rc !=SQLITE_OK)
		LOG("sql error:%s",err_msg);
	return 0;

}

int addtodb(int id,char *name,int kind, char *parent){
	char *err_msg=0;
	char *sql=sqlite3_mprintf("insert into Nodes values(%d,'%s',%d,'%s')",id,name,kind,parent);
	sqlite3_exec(db,sql,0,0,&err_msg);
	sqlite3_free(sql);
	return 0;

}

int scan(char *dir)
{
	DIR *dp;
	struct dirent *dirp;
	struct nodes *kinds;
	char id=0;
	kinds=(struct nodes *)malloc (sizeof(struct nodes));
	kinds->next=NULL;
	LOG("scan dir is %s\n",dir);
	if((dp=opendir(dir)) ==NULL)
		printf("cannot open dir\n");
	while((dirp=readdir(dp)) !=NULL)
	{
		char *path;
		struct stat st;
		int kind,len;
		if(dirp->d_name[0]=='.')
			continue;
		len=strlen(dir)+strlen(dirp->d_name);
		path=(char *)malloc(len);
		sprintf(path,"%s/%s",dir,dirp->d_name);
		if(lstat(path,&st)<0)
			printf("get path info fail\n");

	if(S_ISDIR(st.st_mode))
		kind=1;
	else
		kind=0;
		if(kind==1)
			scan(path);
		else
		LOG("path name:%s,kind:%d,size:%d\n",path,kind,(int)st.st_size);
		addtodb(id,path,kind,dir);
		free(path);
		id++;
	}
	closedir(dp);
	free(kinds);
	return 0;
}

int main(int argc,char *argv[])
{
	system("echo clear > scanlog");
	LOG(" main get scan dir is %s\n",argv[1]);
	int rc=sqlite3_open(DB,&db);
	if(rc !=SQLITE_OK){
		LOG("sql error %s",sqlite3_errmsg(db));
		sqlite3_close(db);
		return 1;
	}
	LOG(" sql open ok\n");
	createtable(db);
	scan(argv[1]);
	sqlite3_close(db);
	return 0;
}

